package com.xuetang9.fujian.net.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @describe:
 * @author:fujian
 * @date:2021/6/12
 * @Version: V1.0
 * @Package: com.xuetang9.fujian.net
 */
@SuppressWarnings("all")
public class ECQServer {
    private ServerSocket serverSocket;
    private Integer port;
    public boolean isRunning;
    private static List<SocketHandler> handlers = new ArrayList<>();

    public ECQServer(int port){
        this.port = port;
        this.isRunning = true;
    }

    public void listener(){
        try {
            serverSocket = new ServerSocket(port);
            System.out.println("server started,wating...");
            while (isRunning){
                Socket socket = serverSocket.accept();
                System.out.println("client connected....");
                SocketHandler handler = new SocketHandler(socket, this);
                new Thread(handler).start();
                handlers.add(handler);
                System.out.println("客户端连接成功：" + socket.getRemoteSocketAddress());
                System.out.println("当前在线人数：" + GetOnLineHandler().size());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public List<SocketHandler> getHandlers() {
        return handlers;
    }

    public SocketHandler getSocketHandler(String key){
        for (SocketHandler handler : handlers) {
            if (handler.getKey().equals(key)){
                return handler;
            }
        }
        return null;
    }

    public static List<SocketHandler> GetOnLineHandler(){
        Iterator<SocketHandler> iterator = handlers.iterator();
        while (iterator.hasNext()){
            if (iterator.next().getStatus() == SocketHandler.CLOSE){
                iterator.remove();
            }
        }
        return handlers;
    }

}
